//
//  CancleOutHolidayViewController.m
//  AttendenceSys
//
//  Created by ld on 16/1/18.
//  Copyright © 2016年 窦芳俊. All rights reserved.
//

#import "CancleOutHolidayViewController.h"

@interface CancleOutHolidayViewController ()

@end



@implementation CancleOutHolidayViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _curPage = _totalPage = 1;
    _cancleOutHolidayArr = [[NSMutableArray alloc] init];
    
    if (!_bApplyClass)
    {
        self.strNavTitle = @"销外出假";
        [self getUserAction:@"3"];
    }
    else
    {
        _applyWeekDayDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"周一",@"1",@"周二",@"2",@"周三",@"3",@"周四",@"4",@"周五",@"5",@"周六",@"6",@"周日",@"7", nil];
        [self getApplyClassRecord:_curPage Type:@"2"];
        self.strNavTitle = @"申请课时假记录";
    }
    
    //[self getUserAction:@"2"];
    
    //[self initData];
    
    [self initView];
}

//消息接口 http://211.65.216.54/getStudentDutyList.action?userCode=xiaohu&page=1&rowNum=10&userType=1(1表示老师2表示学生)
- (void)getApplyClassRecord:(NSInteger)iPag Type:(NSString*)sType
{
    NSString* refer = @"getStudentDutyList.action?";
    NSString* prefix = kASHttpUrl(refer);
    
    NSString* courseUrl = [NSString stringWithFormat:@"%@userCode=%@&page=%@&rowNum=10&userType=%@", prefix, AS_APP_UserCode, [NSString stringWithFormat:@"%ld",(long)iPag],sType];
    
    [SVProgressHUD showWithStatus:@"获取课时假记录" maskType:SVProgressHUDMaskTypeClear];
    ASNetworkEngine *networkingEngine = [ASNetworkEngine sharedInstance];
    
    [networkingEngine GET:courseUrl parameters:nil success:^(id responseObject) {
        
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        jsonRsp = [jsonRsp processDictionaryIsNSNull:jsonRsp];
        
        if (isSuccessRsp(jsonRsp))
        {
//            _curPage = [[jsonRsp objectForKey:kASJsonMsgPage] integerValue];
//            _totalPage = [[jsonRsp objectForKey:kASJsonMsgTotalPage] integerValue];
            NSArray* data = [jsonRsp objectForKey:kASJsonData];
            _cancleOutHolidayArr = [self parseApplyClassRecordListInfo:data];
            //[_cancleOutHolidayArr addObjectsFromArray:arr];
            [self.tableView reloadData];
            [SVProgressHUD dismiss];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:errorMsgRsp(jsonRsp)];
        }
        
        [self reloadData];
        
    } failure:^(NSError *error) {
        
        [self reloadData];
        //[SVProgressHUD showErrorWithStatus:error.description];
        [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];
    }];
}

- (NSMutableArray*)parseApplyClassRecordListInfo:(NSArray*)arr
{
    NSMutableArray* actArray = [[NSMutableArray alloc] init];
    for (unsigned int i = 0; i < arr.count; i++)
    {
        ApplyClassRecordInfo* applyClaRedInfo = [[ApplyClassRecordInfo alloc] init];
        
        NSDictionary* dic = [arr objectAtIndex:i];
        dic = [dic processDictionaryIsNSNull:dic];
        
        applyClaRedInfo.courseNumber = [dic objectForKey:@"courseNumber"];
        applyClaRedInfo.leaveDate = [dic objectForKey:@"leaveDate"];
        applyClaRedInfo.submitDate = [dic objectForKey:@"submitDate"];
        applyClaRedInfo.userCode = [dic objectForKey:@"userCode"];
        applyClaRedInfo.userName = [dic objectForKey:@"userName"];
        applyClaRedInfo.weekDay = [dic objectForKey:@"weekDay"];
        
        applyClaRedInfo.actionDesc = [dic objectForKey:@"actionDesc"];
        applyClaRedInfo.pkApproHistoryId = [dic objectForKey:@"pkApproHistoryId"];
        applyClaRedInfo.portraitNum = [dic objectForKey:@"portraitNum"];
        applyClaRedInfo.imageUrl = [dic objectForKey:@"imageUrl"];
        applyClaRedInfo.actionPicture = [dic objectForKey:@"actionPicture"];
        
        applyClaRedInfo.approveCode = [dic objectForKey:@"approveCode"];
        applyClaRedInfo.courseId = [dic objectForKey:@"courseId"];
        applyClaRedInfo.courseName = [dic objectForKey:@"courseName"];
        
        [actArray addObject:applyClaRedInfo];
    }
    
    return actArray;
}

//查看自己的还未审批的请假历史(供销假用) http://121.42.185.124:8080/LawSchool/getUserAction.action?userCode=xiaohu&status=1 status要获取的状态1按天请假2请课假 返回参数actionStTime请假开始日期actionEnTime请假结束日期actionTypeName请假名称pkUserActionId外出假ID（在学生销假的时候要此字段）别的字段可以不用管了
- (void)getUserAction:(NSString *)sType
{
    NSString* refer = @"getUserAction.action?";
    NSString* prefix = kASHttpUrl(refer);
    
    NSString* courseUrl = [NSString stringWithFormat:@"%@userCode=%@&status=%@", prefix,AS_APP_UserCode,sType];
    
    [SVProgressHUD showWithStatus:@"获取外出假信息" maskType:SVProgressHUDMaskTypeClear];
    ASNetworkEngine *networkingEngine = [ASNetworkEngine sharedInstance];
    
    [networkingEngine GET:courseUrl parameters:nil success:^(id responseObject) {
        
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        jsonRsp = [jsonRsp processDictionaryIsNSNull:jsonRsp];
        if (isSuccessRsp(jsonRsp))
        {
            NSArray* data = [jsonRsp objectForKey:kASJsonData];
            
            NSMutableArray* arr = [self parseUserActionListInfo:data];
            _cancleOutHolidayArr = arr;
            //[_cancleOutHolidayArr addObjectsFromArray:arr];
           
            [self.tableView reloadData];
            [self reloadData];
            [SVProgressHUD dismiss];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:errorMsgRsp(jsonRsp)];
        }
        
    } failure:^(NSError *error) {
        
        //[SVProgressHUD showErrorWithStatus:error.description];
        [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];
    }];
}

- (NSMutableArray*)parseUserActionListInfo:(NSArray*)arr
{
    //ASLoginUserInfo
    NSMutableArray* courseArray = [[NSMutableArray alloc] init];
    for (unsigned int i = 0; i < arr.count; i++)
    {
        CancleOutHolidayInfo* userActionInfo = [[CancleOutHolidayInfo alloc] init];
        NSDictionary* dic = [arr objectAtIndex:i];
        dic = [dic processDictionaryIsNSNull:dic];
        userActionInfo.actionStTime = [dic objectForKey:@"actionStTime"];
        userActionInfo.actionEnTime = [dic objectForKey:@"actionEnTime"];
        userActionInfo.actionTime = [dic objectForKey:@"actionTime"];
        userActionInfo.actionType = [dic objectForKey:@"actionType"];
        userActionInfo.actionTypeName = [dic objectForKey:@"actionTypeName"];
        userActionInfo.actionValue = [dic objectForKey:@"actionValue"];
        userActionInfo.pkUserActionId = [dic objectForKey:@"pkUserActionId"];
        userActionInfo.submitStatus = [dic objectForKey:@"submitStatus"];
        userActionInfo.submitStatusName = [dic objectForKey:@"submitStatusName"];
        userActionInfo.userCode = [dic objectForKey:@"userCode"];
        userActionInfo.userName = [dic objectForKey:@"userName"];
        
        [courseArray addObject:userActionInfo];
    }
    return courseArray;
}

- (void)initView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-49-15-49);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView registerClass:[CancleOutHolidayCell class] forCellReuseIdentifier:NSStringFromClass([CancleOutHolidayCell class])];
    [self.view addSubview:_tableView];
    
    _refresh = [[ASRefreshControl alloc] initWithScrollView:_tableView delegate:self];
    _refresh.topEnabled = YES;
    _refresh.bottomEnabled = YES;
}

- (void)refreshControl:(ASRefreshControl *)refreshControl didEngageRefreshDirection:(RefreshDirection)direction
{
    if (direction == RefreshDirectionTop)
    {
        if (_bApplyClass)
        {
            [self getApplyClassRecord:_curPage Type:@"2"];
        }
        else
        {
            [self getUserAction:@"3"];
        }
    }
    else if (direction == RefreshDirectionBottom)
    {
        if (_bApplyClass)
        {
            [self getApplyClassRecord:_curPage Type:@"2"];
        }
        else
        {
            [self getUserAction:@"3"];
        }
    }
}

- (void)reloadData
{
    if (self.refresh.refreshingDirection == RefreshingDirectionTop)
    {
        [self.refresh finishRefreshingDirection:RefreshDirectionTop];
    }
    else if (self.refresh.refreshingDirection == RefreshingDirectionBottom)
    {
        [self.refresh finishRefreshingDirection:RefreshDirectionBottom];
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_cancleOutHolidayArr count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CancleOutHolidayCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CancleOutHolidayCell class])];
    [cell setBackgroundColor:[UIColor clearColor]];
    
    if (!_bApplyClass)
    {
        CancleOutHolidayInfo* cancleInfo = [_cancleOutHolidayArr objectAtIndex:indexPath.row];
        cell.delegate = self;
        
        if ((nil == cancleInfo.actionTypeName) || (0 == cancleInfo.actionTypeName.length))
        {
            cancleInfo.actionTypeName = @"外出假";
        }
        
        if ((nil == cancleInfo.actionEnTime) || (0 == cancleInfo.actionEnTime.length))
        {
            cell.appBegEndTimeLab.text = [NSString stringWithFormat:@"%@ %@",cancleInfo.actionStTime,cancleInfo.actionTypeName];
        }
        else
        {
            cell.appBegEndTimeLab.text = [NSString stringWithFormat:@"%@至%@ %@",cancleInfo.actionStTime,cancleInfo.actionEnTime,cancleInfo.actionTypeName];
        }
        
        cell.cancleBtn.hidden = YES;
        cell.cancleBtn.tag = indexPath.row;
        if ([cancleInfo.submitStatus isEqualToString:@"2"])
        {
            cell.cancleBtn.hidden = NO;
        }
        
        cell.appTimeLab.text = [NSString stringWithFormat:@"申请时间: %@",cancleInfo.actionTime];
        //cell.appInfoLab.text = [cell appInfoForAppType:cancleInfo.appType];
        cell.appInfoLab.text = cancleInfo.submitStatusName;
        
        cell.msgDesc.text = @"";
    }
    else
    {
        ApplyClassRecordInfo* applyClassRec = [_cancleOutHolidayArr objectAtIndex:indexPath.row];
        //cell.delegate = self;
        NSString* appBegEndTime = @"";
        
        if (!((nil == applyClassRec.leaveDate) || (0 == applyClassRec.leaveDate.length)))
        {
            appBegEndTime = [NSString stringWithFormat:@"请假日期 %@", applyClassRec.leaveDate];
        }
        if (!((nil == applyClassRec.weekDay) || (0 == applyClassRec.weekDay.length)))
        {
            appBegEndTime = [NSString stringWithFormat:@"%@ %@",appBegEndTime, [_applyWeekDayDic objectForKey:applyClassRec.weekDay]];
        }
        if (!((nil == applyClassRec.courseName) || (0 == applyClassRec.courseName.length)))
        {
            appBegEndTime = [NSString stringWithFormat:@"%@ %@",appBegEndTime, applyClassRec.courseName];
        }
        cell.appBegEndTimeLab.text = appBegEndTime;
        
        // reset
        cell.cancleBtn.hidden = YES;
        cell.cancleBtn.enabled = YES;
        cell.cancleBtn.backgroundColor = RGB(252, 119, 62);

        [self updateCellButtonStatus:applyClassRec designatedCell:cell];
        
        cell.appTimeLab.frame = CGRectMake(15,
                                           Cancle_OutHolidayHeight/2-5,
                                           [UIScreen mainScreen].bounds.size.width*2/3,
                                           20);
        cell.appTimeLab.text = [NSString stringWithFormat:@"申请时间: %@", applyClassRec.submitDate];
        
        cell.appInfoLab.frame = CGRectMake([UIScreen mainScreen].bounds.size.width-25-40-30,
                                           cell.appBegEndTimeLab.frame.origin.y,
                                           80,
                                           cell.appBegEndTimeLab.frame.size.height);
        //cell.appInfoLab.text = [NSString stringWithFormat:@"第%@节课", applyClassRec.courseNumber];
        cell.appInfoLab.text = @"";
        
        cell.msgDesc.text = applyClassRec.actionDesc;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return Cancle_OutHolidayHeight+10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //    DcNAppProNotiMeetInfo* approveInfo = [_tmpArray objectAtIndex:[indexPath row]];
    //    DcNItemInfoViewController* itemInfoVC = [[DcNItemInfoViewController alloc] init];
    //    [itemInfoVC saveURL:approveInfo.pageLink];
    //
    //    [self.navigationController pushViewController:itemInfoVC animated:YES];
}

- (void)cancleOutHoliday:(NSInteger)iTag
{
    CancleOutHolidayInfo* cancleInfo = [_cancleOutHolidayArr objectAtIndex:iTag];
    [self cancleOutHolidayforStudent:cancleInfo.pkUserActionId];
}

//销假接口 http://121.42.185.124:8080/LawSchool/cancelAction.action?userCode=xiaohu&pkUserActionId=11111111111111
- (void)cancleOutHolidayforStudent:(NSString*)userActionId
{
    NSString* refer = @"cancelAction.action?";
    NSString* prefix = kASHttpUrl(refer);
    
    NSString* inActUrl = [NSString stringWithFormat:@"%@userCode=%@&pkUserActionId=%@", prefix,AS_APP_UserCode,userActionId];
    
    [SVProgressHUD showWithStatus:@"销外出假..." maskType:SVProgressHUDMaskTypeClear];
    ASNetworkEngine *networkingEngine = [ASNetworkEngine sharedInstance];
    [networkingEngine GET:inActUrl parameters:nil success:^(id responseObject) {
        
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        jsonRsp = [jsonRsp processDictionaryIsNSNull:jsonRsp];
        
        if (isSuccessRsp(jsonRsp))
        {
            [SVProgressHUD showErrorWithStatus:errorDataInfoRsp(jsonRsp)];
            
            for (unsigned int i = 0; i < _cancleOutHolidayArr.count; i++)
            {
                CancleOutHolidayInfo* cancleInfo = [_cancleOutHolidayArr objectAtIndex:i];
                if ([cancleInfo.pkUserActionId isEqualToString:userActionId])
                {
                    [_cancleOutHolidayArr removeObject:cancleInfo];
                    break;
                }
            }
            
            [self.tableView reloadData];
            [SVProgressHUD dismiss];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:errorMsgRsp(jsonRsp)];
        }
        
    } failure:^(NSError *error) {
        
        //[SVProgressHUD showErrorWithStatus:error.description];
        [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)updateCellButtonStatus:(ApplyClassRecordInfo *)info designatedCell:(CancleOutHolidayCell *)cell
{
    // 根据approveCode 展示对应请假消息审批状态 // approveCode 1审批通过 2审批不通过 3待审批 4已经撤销
    if ([info.approveCode isEqualToString:@"1"])
    {
        cell.cancleBtn.hidden = NO;
        cell.cancleBtn.enabled = NO;
        cell.cancleBtn.backgroundColor = RGB(167, 167, 167);
        [cell.cancleBtn setTitle:@"已同意" forState:UIControlStateDisabled];
    }
    else if ([info.approveCode isEqualToString:@"2"])
    {
        cell.cancleBtn.hidden = NO;
        cell.cancleBtn.enabled = NO;
        cell.cancleBtn.backgroundColor = RGB(167, 167, 167);
        [cell.cancleBtn setTitle:@"不通过" forState:UIControlStateDisabled];
    }
    else if ([info.approveCode isEqualToString:@"3"])
    {
        cell.cancleBtn.hidden = NO;
        cell.cancleBtn.enabled = NO;
        cell.cancleBtn.backgroundColor = RGB(167, 167, 167);
        [cell.cancleBtn setTitle:@"待审批" forState:UIControlStateDisabled];
    }
    else if ([info.approveCode isEqualToString:@"4"])
    {
        cell.cancleBtn.hidden = NO;
        cell.cancleBtn.enabled = NO;
        cell.cancleBtn.backgroundColor = RGB(167, 167, 167);
        [cell.cancleBtn setTitle:@"已撤销" forState:UIControlStateDisabled];
    }
}

@end




